package cn.com.agree.mybatisporelation.one2one.bothsides.service.impl;

import cn.com.agree.mybatisporelation.one2one.bothsides.controller.dto.PassportDTO;
import cn.com.agree.mybatisporelation.one2one.bothsides.dao.mapper.PassportMapper;
import cn.com.agree.mybatisporelation.one2one.bothsides.dao.mapper.PersonMapper;
import cn.com.agree.mybatisporelation.one2one.bothsides.dao.po.PassportPO;
import cn.com.agree.mybatisporelation.one2one.bothsides.dao.po.PersonPO;
import cn.com.agree.mybatisporelation.one2one.bothsides.service.PassportService;
import cn.com.agree.mybatisporelation.one2one.bothsides.service.exception.BizPassportException;
import cn.hutool.core.bean.copier.BeanCopier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
public class PassportServiceImpl implements PassportService {

    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private PassportMapper passportMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PassportDTO addPassport(PassportDTO passportDTO) {
        if (Objects.isNull(passportDTO.getPerson()) || Objects.isNull(passportDTO.getPerson().getId())) {
            throw new BizPassportException("旅人不能为空。");
        }
        PersonPO personPO = personMapper.selectById(passportDTO.getPerson().getId());
        if (Objects.isNull(personPO)) {
            throw new BizPassportException("旅人不存在。");
        }

        PassportPO passportPO = BeanCopier.create(passportDTO, new PassportPO(), null).copy();
        passportPO.setPerson(personPO);
        passportMapper.insert(passportPO);

        personPO.setPassport(passportPO);
        personMapper.updateById(personPO);

        return BeanCopier.create(passportPO, new PassportDTO(), null).copy();
    }

    @Override
    public PassportDTO getPassport(Long id) {
        PassportPO passportPO = passportMapper.findById(id);
        return BeanCopier.create(passportPO, new PassportDTO(), null).copy();
    }
}